package com.server.net.message;

import com.server.game.logic.login.POffline;
import com.server.net.session.Session;
import com.server.util.ConfPropertiesUtil;
import com.server.util.LogUtil;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 分发协议
 */
public class MsgDispatcherManager {

    private static MsgDispatcherManager instance = new MsgDispatcherManager();

    public static MsgDispatcherManager getInstance() {
        return instance;
    }

    //所有dispatcher集合管理
    private Map<Integer, MsgDispatcher> dispatchers = new ConcurrentHashMap<>();
    //所有角色对应场景id   token<>dispatcherId
    private final Map<String, Integer> role2dispatcher = new ConcurrentHashMap<>();

    private boolean start = false;

    public void init() {
        if (dispatchers.isEmpty()) {
            for (int i = 0; i < ConfPropertiesUtil.getInstance()._MSG_THREAD_NUM; i++) {
                MsgDispatcher dispatcher = new MsgDispatcher();
                dispatchers.put(i, dispatcher);
                dispatcher.startUp();
            }
            this.start = true;
        }
    }

    public void onLine(String toke) {
        if (!this.start) {
            return;
        }
        if (role2dispatcher.containsKey(toke)) {
            return;
        }
        int index = (int) (System.currentTimeMillis() % ConfPropertiesUtil.getInstance()._MSG_THREAD_NUM);
        role2dispatcher.put(toke, index);
    }

    public void offLine(Session session) {
        new POffline(session.getToken(), session.getRoleId()).submit();
        role2dispatcher.remove(session.getToken());
    }

    public void close() {
        LogUtil.game.info("MsgDispatcherManager close begin");
        this.start = false;
        dispatchers.forEach((k, v) -> {
            v.close();
        });
        LogUtil.game.info("MsgDispatcherManager close end");
    }

    private MsgDispatcher getScene(String token) {
        if (!role2dispatcher.containsKey(token)) {
            return null;
        }
        int index = role2dispatcher.get(token);
        return dispatchers.get(index);
    }

    public void addMessagePack(MsgPack msgPack) {
        if (!this.start) {
            return;
        }
        MsgDispatcher scene = getScene(msgPack.getToken());
        if (null == scene) {
            return;
        }
        scene.addMessagePack(msgPack);
    }

}
